package com.passion.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

/**
 * @program offline-e-commerce-data-warehouse
 * @Description
 * @Author limeihua
 * @Date 2024/10/07 16:45
 * @Version 1.0
 */
public class ExcelUtil {
    public static SXSSFWorkbook JsonArrayToExcel(String result) {
        JSONArray jsonArray = JSONArray.parseArray(result);
        JSONObject one = (JSONObject) jsonArray.get(0);

        SXSSFWorkbook workbook = new SXSSFWorkbook();
        Sheet sheet = workbook.createSheet("sheet1");
        Row headerRow = sheet.createRow(0);
        String[] columns = {"Column1", "Column2", "Column3"};
        for (int i = 0; i < columns.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(columns[i]);
        }
        return workbook;
    }


    private static void mergeSameValueRowCells(Sheet sheet, Row row) {
        int lastCellNum = row.getLastCellNum();
        if (lastCellNum <= 0) return;

        Cell firstCell = row.getCell(0);
        if (firstCell == null || firstCell.getCellType() != CellType.STRING) return;

        String currentValue = firstCell.getStringCellValue();
        int startCol = 0;
        for (int colIndex = 1; colIndex < lastCellNum; colIndex++) {
            Cell nextCell = row.getCell(colIndex);
            if (nextCell == null || nextCell.getCellType() != CellType.STRING || !currentValue.equals(nextCell.getStringCellValue())) {
                if (colIndex - startCol > 1) {
                    sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), startCol, colIndex - 1));
                }
                if (nextCell != null && nextCell.getCellType() == CellType.STRING) {
                    currentValue = nextCell.getStringCellValue();
                    startCol = colIndex;
                }
            }
        }
        // 合并最后一组连续相同值的单元格
        if (lastCellNum - startCol > 1) {
            sheet.addMergedRegion(new CellRangeAddress(row.getRowNum(), row.getRowNum(), startCol, lastCellNum - 1));
        }
    }
}
